package cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.login.CheckMobileActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.recharge.BuyActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.user.ActCertification;
import cn.com.xinjinfu.pdoulcProduct.adapter.MenuItemAdapter;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.FixedProductInfoBean;
import cn.com.xinjinfu.pdoulcProduct.entity.FixedProductInfoBean.Bid;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.view.BaseGridView;
import cn.com.xinjinfu.pdoulcProduct.view.CustomViewPager;
import cn.com.xinjinfu.pdoulcProduct.view.LoadStatusBox;
import cn.com.xinjinfu.pdoulcProduct.view.ScrollViewContainer;

public class FirstInvestAct extends BaseActivity implements View.OnClickListener{

    private LoadStatusBox loadbox;

    private ArrayList<View> viewContainter = new ArrayList<View>();
    private CustomViewPager pager;
    private LayoutParams linearParams;
    private TextView tv_status2,tv_time_info,tv_time,tv_money,tv_apr,tv_zonge,tv_qitou,tv_shengyu,tv_shouyi_text,tv_fanhuan_text,
            tv_object_name, tv_nian_shouyilv, tv_rongzi_money, tv_danbao_organization, tv_huankuan_style, tv_borrower_name, tv_id_number,
            tv_sex, tv_age, tv_marital_status, tv_current_city, tv_property_located, tv_building_area,tv_company_describe,tv_company_name,
            tv_company_time,tv_company_ceo,tv_company_money,tv_company_friends,tv_evaluated_price, risk_info;
    private LinearLayout ll_borrower, ll_company, ll_house, ll_company_describe;
    private String bidId;
    private String title;
    private FixedProductInfoBean firstInfoBean;
    private MenuItemAdapter saMenuItem;

    private RequestQueue requen;
    private Button bt_mairu;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_invest);
        ActivityManager.getInstance().addActivity(this);
        Intent intent = getIntent();
        bidId = intent.getStringExtra("bidId");//得到对应的bidId值
        title = intent.getStringExtra("title");
        TitleManager.showTitle(this, title, "");
        initView();
        //pager适配器
        pager.setAdapter(new PagerAdapter() {
            //viewpager中的组件数量
            @Override
            public int getCount() {
                return viewContainter.size();
            }

            //滑动切换的时候销毁当前的组件
            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                ((ViewPager) container).removeView(viewContainter.get(position));
            }

            //每次滑动的时候生成的组件
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ((ViewPager) container).addView(viewContainter.get(position));
                return viewContainter.get(position);
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getItemPosition(Object object) {
                return super.getItemPosition(object);
            }

        });
        requen = Volley.newRequestQueue(this);
        loginRequest();
    }

    private void initView(){
        loadbox = (LoadStatusBox) this.findViewById(R.id.loadStatusBox);
        loadbox.setOnClickListener(this);
        loadbox.loading();
        ScrollViewContainer svc = (ScrollViewContainer) findViewById(R.id.contaoner);
        pager = (CustomViewPager)findViewById(R.id.viewpager);
        pager.setScanScroll(true);//禁止左右滑动
        bt_mairu = (Button)findViewById(R.id.bt_mairu);
        bt_mairu.setOnClickListener(this);
        tv_status2 = (TextView)findViewById(R.id.tv_status2);
        tv_time_info = (TextView)findViewById(R.id.tv_time_info);
        tv_time = (TextView)findViewById(R.id.tv_time);
        tv_money = (TextView)findViewById(R.id.tv_money);
        tv_apr = (TextView)findViewById(R.id.tv_apr);
        tv_zonge = (TextView)findViewById(R.id.tv_zonge);
        tv_qitou = (TextView)findViewById(R.id.tv_qitou);
        tv_shengyu = (TextView)findViewById(R.id.tv_shengyu);

        View view1 = LayoutInflater.from(this).inflate(R.layout.first_invest_tab1, null);
        View view2 = LayoutInflater.from(this).inflate(R.layout.first_invest_tab2, null);
        tv_shouyi_text = (TextView)view1.findViewById(R.id.tv_shouyi_text);
        tv_fanhuan_text = (TextView)view1.findViewById(R.id.tv_fanhuan_text);

        tv_object_name = (TextView) view2.findViewById(R.id.tv_object_name);
        tv_nian_shouyilv = (TextView) view2.findViewById(R.id.tv_nian_shouyilv);
        tv_rongzi_money = (TextView) view2.findViewById(R.id.tv_rongzi_money);
        tv_danbao_organization = (TextView) view2.findViewById(R.id.tv_danbao_organization);
        tv_huankuan_style = (TextView) view2.findViewById(R.id.tv_huankuan_style);

        tv_borrower_name = (TextView) view2.findViewById(R.id.tv_borrower_name);
        tv_id_number = (TextView) view2.findViewById(R.id.tv_id_number);
        tv_sex = (TextView) view2.findViewById(R.id.tv_sex);
        tv_age = (TextView) view2.findViewById(R.id.tv_age);
        tv_marital_status = (TextView) view2.findViewById(R.id.tv_marital_status);
        tv_current_city = (TextView) view2.findViewById(R.id.tv_current_city);

        tv_property_located = (TextView) view2.findViewById(R.id.tv_property_located);
        tv_building_area = (TextView) view2.findViewById(R.id.tv_building_area);
        tv_evaluated_price = (TextView) view2.findViewById(R.id.tv_evaluated_price);

        ll_borrower = (LinearLayout) view2.findViewById(R.id.ll_borrower);
        ll_company = (LinearLayout) view2.findViewById(R.id.ll_company);
        ll_house = (LinearLayout) view2.findViewById(R.id.ll_house);
        ll_company_describe = (LinearLayout) view2.findViewById(R.id.ll_company_describe);

        tv_company_describe = (TextView) view2.findViewById(R.id.tv_company_describe);
        tv_company_name = (TextView) view2.findViewById(R.id.tv_company_name);
        tv_company_time = (TextView) view2.findViewById(R.id.tv_company_time);
        tv_company_ceo = (TextView) view2.findViewById(R.id.tv_company_ceo);
        tv_company_money = (TextView) view2.findViewById(R.id.tv_company_money);
        tv_company_friends = (TextView) view2.findViewById(R.id.tv_company_friends);
        risk_info = (TextView) view2.findViewById(R.id.risk_info);
        /** 最下面的GridView*/
        BaseGridView gridview = (BaseGridView) view2.findViewById(R.id.gridView);
        saMenuItem = new MenuItemAdapter(this);
        gridview.setAdapter(saMenuItem);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                                                System.out.println("click index:" + arg2);
                                            }
                                        }
        );
        RelativeLayout biao_info = (RelativeLayout)view1.findViewById(R.id.biao_info);
        RelativeLayout tv_shoutou = (RelativeLayout)view2.findViewById(R.id.tv_shoutou);
        biao_info.setOnClickListener(this);
        tv_shoutou.setOnClickListener(this);
        viewContainter.add(view1);
        viewContainter.add(view2);
        linearParams = (LayoutParams) pager.getLayoutParams();      // 取控件mGrid当前的布局参数
    }

    private void upData(JSONObject jobj){
        firstInfoBean = JSON.parseObject(jobj.toString(), FixedProductInfoBean.class);
        Bid bid = firstInfoBean.getBid();
        double shengyu = bid.getAmount() - bid.getHasInvestedAmount();
        if (shengyu<=0){
            tv_status2.setText("已结束");
//            bt_mairu.setBackgroundColor(0xFFFFBDCE);
//            bt_mairu.setText("已结束");
            bt_mairu.setVisibility(View.GONE);
            bt_mairu.setEnabled(false);
        }else {
            tv_status2.setText("投标中");
            bt_mairu.setBackgroundColor(0xffF06E82);
            bt_mairu.setEnabled(true);
            bt_mairu.setText("立即购买");
        }
        //新手标 期限单位现在都为：日
        if (bid.getPeriodUnit() == 0){
            tv_time_info.setText("期限（月）");
        }else if (bid.getPeriodUnit() == 1){
            tv_time_info.setText("期限（天）");
        }else {
            tv_time_info.setText("期限（年）");
        }
        tv_time.setText(bid.getPeriod()+"");
        tv_money.setText(TextViewUtil.getSumLength(firstInfoBean.getMaxNewBidInvestAmount()));
        tv_apr.setText(NumberFormat.getInstance().format(bid.getApr())+"%");
        tv_zonge.setText(TextViewUtil.getSumLength(bid.getAmount()));
        tv_qitou.setText(TextViewUtil.getSumLength(bid.getMinInvestAmount()));
        tv_shengyu.setText(TextViewUtil.getSumLength(shengyu));

        tv_shouyi_text.setText((int)bid.getMinInvestAmount()+"元起投，上限"+firstInfoBean.getMaxNewBidInvestAmount()+"元，" +
                "投资期限"+bid.getPeriod()+"天，预计年化收益率"+(int)bid.getApr()+"%。");
        tv_fanhuan_text.setText("投资当日开始计息，第"+bid.getPeriod()+"日平台将自动返还本息至您的可用余额。提现T+1日到账。");

    /**
     * 公共信息   根据ProductId来判断对应的模块显示
     *              新手标里不用判断
     */
        int id = bid.getProductId();
        if (id == 7) {
            ll_company_describe.setVisibility(View.VISIBLE);
            ll_borrower.setVisibility(View.GONE);
            ll_company.setVisibility(View.VISIBLE);
            ll_house.setVisibility(View.GONE);
            tv_company_describe.setText("   " + bid.getDescription());
            tv_company_name.setText(bid.getCompanyName());
            String time = bid.getSetupTime();
            String show_id = time.substring(0, 2) + "**" + time.substring(4);
            tv_company_time.setText(show_id);
            tv_company_ceo.setText(bid.getCompanyLegal().substring(0, 1) + "**");
            tv_company_money.setText(bid.getRegisterCapital());
            tv_company_friends.setText(bid.getCooperation());

        } else if (id == 1 || id == 11) {
            ll_company_describe.setVisibility(View.GONE);
            ll_borrower.setVisibility(View.VISIBLE);
            ll_company.setVisibility(View.GONE);
            ll_house.setVisibility(View.VISIBLE);
        } else {
            ll_company_describe.setVisibility(View.GONE);
            ll_borrower.setVisibility(View.VISIBLE);
            ll_company.setVisibility(View.GONE);
            ll_house.setVisibility(View.GONE);
        }

        //基本信息
        tv_object_name.setText(bid.getTitle());
        tv_nian_shouyilv.setText(NumberFormat.getInstance().format(bid.getApr()) + "%");
        tv_rongzi_money.setText(NumberFormat.getInstance().format(bid.getAmount() / 10000) + " 万");//融资近额  100万
        tv_danbao_organization.setText(bid.getAgencyName());                //揭开
        tv_huankuan_style.setText(bid.getRepayment().getName());

        //借款人信息id.substring(0, 3) + "********" + id.substring(14);
        tv_borrower_name.setText(bid.getUser().getRealityName().substring(0, 1) + "**");
        tv_id_number.setText(bid.getUser().getIdNumber().substring(0, 4) + "*******"
                + bid.getUser().getIdNumber()
                .substring(bid.getUser().getIdNumber().length()));
        tv_sex.setText(bid.getUser().getSex());
        tv_age.setText(bid.getUser().getAge() + "");
        tv_marital_status.setText(bid.getUser().getMaritalName());
        tv_current_city.setText(bid.getUser().getAddress());

        //房产信息
        if (bid.getLocation() != null
                && bid.getLocation().length() >= 8){
            tv_property_located.setText(bid.getLocation().substring(0, 8) + "********");
        }else {
            tv_property_located.setText(bid.getLocation());
        }
        tv_building_area.setText(bid.getBuildArea() + "㎡");
        tv_evaluated_price.setText(bid.getAssessmentPrice());

        //风控信息
        risk_info.setText(Html.fromHtml(bid.getRiskInfo()));
        List<String> page = firstInfoBean.getAudititems();
        saMenuItem.setList(page);
        saMenuItem.notifyDataSetChanged();
    }
    /**
     * 网络请求
     */
    private void loginRequest() {
        if (!DataHandler.isNetworkConnected(this)) {
            loadbox.failed();
            return;
        }
        final Map<String, String> parameters = DataHandler.getParameters("1214");
        parameters.put("bidId", bidId);
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, DataHandler.getEor(this, loadbox));
        requen.add(request);
    }

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("首投专享 ==========" + jobj);
            if (JSONManager.getError(jobj) == -1) {
                loadbox.success();
                upData(jobj);
            } else {
                ToastManager.showShort(FirstInvestAct.this, JSONManager.getMsg(jobj));
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.biao_info:
                linearParams.height = NewUtil.dip2px(this,900.0f);             // 当控件的高强制设成2000象素
                pager.setLayoutParams(linearParams);
                pager.setCurrentItem(1);
                break;
            case R.id.tv_shoutou:
                linearParams.height = NewUtil.dip2px(this,500.0f);          // 当控件的高强制设成1000象素
                pager.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件myGrid
                pager.setCurrentItem(0);
                break;
            case R.id.bt_mairu:
                User user = AccountManager.getInstance().getUser();
                if (user != null && user.getCurrUser().isLogged()) {
                    if (user.getCurrUser().getIdNumber() == null) {
                        Intent intent0 = new Intent();
                        intent0.putExtra("cer_style_falg", 1);
                        intent0.setClass(FirstInvestAct.this, ActCertification.class);
                        startActivity(intent0);
                        ToastManager.showShort(FirstInvestAct.this, "请先进行实名认证！");
                    }else {
                        Intent intent = new Intent(FirstInvestAct.this, BuyActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("objBuy", 0);
                        bundle.putString("Id", bidId);
                        bundle.putString("titlename", title);
                        bundle.putString("xiane", firstInfoBean.getMaxNewBidInvestAmount()+"");
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                } else {
                    startActivity(new Intent(FirstInvestAct.this, CheckMobileActivity.class));
                }
                break;
            default:
                break;
        }
    }
}







//        svc.setOnSecondViewShowListener(new ScrollViewContainer.OnSecondViewShowListener() {
//            @Override
//            public void onSecondViewShow() {
//                Toast.makeText(FirstInvestAct.this, "打开第二界面", Toast.LENGTH_SHORT).show();
//            }
//        });
//
//        svc.setOnUpPullHintListener(new ScrollViewContainer.OnUpPullHintListener() {
//            @Override
//            public void onUpPullHintListener(int state) {
//                if (state == STATE_UP) {
//                    Toast.makeText(FirstInvestAct.this, "继续上拉", Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(FirstInvestAct.this, "回宫", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });